/*
 * @lc app=leetcode.cn id=892 lang=javascript
 *
 * [892] 三维形体的表面积
 */

// @lc code=start
/**
 * @param {number[][]} grid
 * @return {number}
 */
var surfaceArea = function(grid) {
    let sum=0
    for(let i=0;i<grid.length;i++){
        for(let j=0;j<grid[0].length;j++){
            sum+=grid[i][j]*4+2*(grid[i][j]==0?0:1)
            if(i>0)sum-=Math.min(grid[i][j],grid[i-1][j])
            if(i<=grid.length-2)sum-=Math.min(grid[i][j],grid[i+1][j])
            if(j>0)sum-=Math.min(grid[i][j],grid[i][j-1])
            if(j<grid[0].length-1)sum-=Math.min(grid[i][j],grid[i][j+1])
        }
    }
    return sum
};
// @lc code=end

surfaceArea([[1,0],[0,2]])